// lib/api/post_api.dart
import 'package:dio/dio.dart';
import '../models/response.dart';
import '../models/post.dart'; // Import Post model
import 'dio_client.dart';

class PostApi {
  final Dio _dio = DioClient().dio;

  /// 获取帖子列表
  /// [communityId] 可以是可选的，用于筛选特定社区的帖子
  Future<ResponseSuccess<List<Post>>> getPosts({int? communityId}) async {
    try {
      String path = '/post'; // 默认获取所有帖子
      if (communityId != null) {
        path = '/community/$communityId/posts'; // 假设获取特定社区帖子的API路径
      }
      final response = await _dio.get(path);
      return ResponseSuccess.fromJson(
        response.data,
            (json) => (json as List).map((e) => Post.fromJson(e as Map<String, dynamic>)).toList(),
      );
    } on DioException catch (e) {
      throw e.response?.data['msg'] ?? '获取帖子列表失败。';
    } catch (e) {
      throw '获取帖子列表发生未知错误: $e';
    }
  }

  /// **新增：获取帖子详情**
  Future<ResponseSuccess<Post>> getPostDetail(String postId) async { // postId 为 String 类型
    try {
      final response = await _dio.get('/post/$postId'); // 获取帖子详情的 API 路径
      // 使用 ResponseSuccess 泛型解析响应
      return ResponseSuccess.fromJson(
        response.data,
            (json) => Post.fromJson(json as Map<String, dynamic>),
      );
    } on DioException catch (e) {
      // 捕获 Dio 错误，并尝试从响应中获取错误信息
      throw e.response?.data['msg'] ?? '获取帖子详情失败，请稍后再试。';
    } catch (e) {
      // 其他未知错误
      throw '获取帖子详情发生未知错误: $e';
    }
  }

// TODO: 其他帖子相关的API方法，例如 createPost, searchPosts, votePost 等
}